<script lang="ts">
/**
 * @author leo
 * @description #19533 文件上传视图
 * @event $emit('on-cancel') 取消事件
 * @event $emit('on-done') 完成事件
 */

import { Component, Vue, Prop, Watch, Emit } from "vue-property-decorator";
import { EventBus } from "feok-lib";
import OSSFileUpload from "@/components/OSSFileUpload.vue";
import GroupSelect from "@/components/GroupSelect";
import ChoosePhoto from "@/components/ChoosePhoto";

import { postApiAssetsFile, putApiAssetsFileId } from "@/model";

@Component({
  components: {
    OSSFileUpload,
    GroupSelect,
    ChoosePhoto
  }
})
export default class UploadOtherForm extends Vue {
  get rules() {
    return {
      pics: [{ validator: this.checkPic, trigger: "blur" }],
      group_id: [
        { required: true, message: "此项为必填项", trigger: ["blur", "change"] }
      ]
    };
  }

  @Prop() public groupId!: string; // 分组Id
  @Prop() public videoId!: string; // 文件Id
  @Prop() public obj!: any; // 文件Id

  public vLoading = false; // 页面初始化时，loading状态
  public form: any = {
    pics: [],
    group_id: "",
    type: "FILE" // 封面名称
  };

  @Emit()
  public onCancel() {}

  // 校验上传图片
  public checkPic(rule: any, value: any, callback: any) {
    if (value.length === 0) {
      callback(new Error("此处为必填项"));
    } else {
      callback();
    }
  }

  /**
   * 表单验证
   */
  public checkForm() {
    return new Promise((resolve, reject) => {
      const $form = this.$refs.form as any;
      $form.validate((valid: any) => {
        if (valid) {
          resolve(true);
        } else {
          // EventBus.$emit('error', '表单验证失败');
          reject(false);
        }
      });
    });
  }

  /**
   * 拉取数据
   */
  public async fetchFormData() {
    this.form.group_id = this.obj.group_id;
  }

  // 文件上传成功
  public onSuccess(response: any, file: any, fileList: any) {
    const obj = {
      name: file.name,
      url: file.response.url,
      type: "FILE", // 分类 IMAGE VIDEO FILE
      size: file.size // 文件大小
    };
    this.form.pics.push(obj);
  }

  // 文件移除
  public handleRemove(file: any, fileList: any) {
    const arr = this.form.pics.map((res: any) => res.url);
    const index = arr.findIndex((item: any) => {
      return item === file.response.url;
    });
    this.form.pics.splice(index, 1);
  }

  /**
   * 提交表单
   */
  private async submitForm() {
    const valid = await this.checkForm(); // 表单验证
    const res = "";
    if (valid) {
      this.vLoading = true;
      try {
        if (this.videoId) {
          // 编辑
          await putApiAssetsFileId({
            id: this.videoId,
            groupId: this.form.group_id // 分组ID
          });
        } else {
          // 新增
          await postApiAssetsFile(
            this.form.pics.map((res: any) => ({
              ...res,
              groupId: this.form.group_id
            }))
          );
        }
        EventBus.$emit("success", "操作成功");
        this.$emit("on-done");
      } catch (error) {}
      this.vLoading = false;
    }
  }

  private mounted() {
    if (this.videoId) {
      this.fetchFormData();
    }
  }
}
</script>

<template>
  <div v-loading="vLoading" class="upload_file_form">
    <el-form :model="form" :rules="rules" ref="form" label-width="100px">
      <el-form-item label="本地文件：" prop="video" v-if="!this.videoId">
        <OSSFileUpload
          :limit="10"
          :maxSize="1024*1024"
          @on-success="onSuccess"
          @on-remove="handleRemove"
        ></OSSFileUpload>
        <p class="mark">文件大小不超过1G</p>
      </el-form-item>
      <el-form-item label="分组：" prop="group_id">
        <GroupSelect v-model="form.group_id" :query="{type: 'FILE'}"></GroupSelect>
      </el-form-item>
      <el-form-item label>
        <el-button type="primary" class="content-modal__footer__btn" @click="submitForm">保存</el-button>
        <el-button class="content-modal__footer__btn" @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="less">
.upload_file_form {
  .mark {
    font-size: 12px;
    color: #ccc;
  }
}
.upload_file_form_dialog {
  margin-top: 54px !important;
}
.upload_file_form_img {
  display: block;
  width: 200px;
  height: 200px;
  border: 1px dashed #ccc;
  margin-top: 10px;
  text-align: center;
  border-radius: 4px;
  img {
    max-width: 198px;
    max-height: 198px;
  }
}
</style>